package com.redbox.RedboxManagment.controllers;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.redbox.RedboxManagment.ejb.User;
import com.redbox.RedboxManagment.service.ICardService;
import com.redbox.RedboxManagment.service.IUserService;

@Controller
@SessionAttributes("user")
public class LoginController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ICardService cardService;
		
	@RequestMapping(value = "**/login", method = RequestMethod.GET)
	@Transactional
	public ModelAndView home (Locale locale, Model model) {
		
		ModelAndView x = new ModelAndView();
		x.setViewName("login");
		return x;
	}
	
	@RequestMapping(value = "**/login/checkLogin", method = RequestMethod.POST)
	@Transactional
	public ModelAndView checkLogin (Locale locale, Model model,HttpServletRequest request) {
		
		ModelAndView x = new ModelAndView();

		String userName = (String)request.getParameter("txtUser");
		String userPassword = (String)request.getParameter("txtPass");
		
		User user = userService.retrieveUsingName(userName);
		
		if( user == null){
			x.setViewName("redirect:/login");
		}else if(user.getPassword().equals(userPassword)){
			x.setViewName("redirect:/home");
			model.addAttribute("user", user);
		}else{
			x.setViewName("redirect:/login");
		}
			
		return x;
	}
}
